const Koa = require('koa')
const path = require('path')
const serve = require('koa-static')
const views = require('koa-views')
const session = require('koa-session')
const bodyParser = require('koa-bodyparser')
const router = require('./routes')
// CORS是一个W3C标准，全称是"跨域资源共享"（Cross-origin resource sharing）。
// 下面以koa2-cors为例，
const cors = require('koa2-cors')
const koaNunjucks = require('koa-nunjucks-2')
const CONFIG = require('./config/index')

const app = module.exports = new Koa()

// 具体参数我们在后面进行解释
app.use(cors({
  origin: function (ctx) {
    if (ctx.url === '/test') {
      return "*"; // 允许来自所有域名请求
    }
    return 'http://localhost:3000'; // 这样就能只允许 http://localhost:8080 这个域名的请求了
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

app.use(bodyParser())

app.use(serve(
  path.join(__dirname, 'public')
))

app.use(koaNunjucks({
  ext: 'njk',
  path: path.join(__dirname, './views'),
  nunjucksConfig: {
    trimBlocks: true
  }
}))
// app.use(views(path.join(__dirname, './views'), {
//   extension: 'njk',
//   map: { html: 'nunjucks' }
// }))

app.use(session({
  key: CONFIG.session.key,
  maxAge: CONFIG.session.maxAge
}, app))

router(app)

// app.listen(3000);

var server = app.listen(3000, '127.0.0.1', function() {
  const host = server.address().address
  const port = server.address().port

  // console.log('\033[42;30m APP running at:\033[40;32m' + `\n- Local:   http://localhost:${port}\n- Network: http://${host}:${port}`)
  console.log('APP running at:' + `\n- Local:   http://localhost:${port}\n- Network: http://${host}:${port}`)
});
